package com.mce.nebula.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户源服务
 * 对应Python的UserSourceView - 飞书API集成功能
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserSourceService {
    
    private final ObjectMapper objectMapper;
    
    /**
     * 发送飞书消息
     */
    public Map<String, Object> sendFeishuMessage(String smsType, String receiveIdType, String content) {
        try {
            // 从环境变量获取配置参数
            String appId = getEnvVariable("FEISHU_APP_ID");
            String appSecret = getEnvVariable("FEISHU_APP_SECRET");
            String receiveId = getEnvVariable("FEISHU_DEFAULT_RECEIVE_ID");
            
            // 根据短信类型选择不同的配置
            if ("rainbond".equals(smsType)) {
                appId = getEnvVariable("FEISHU_TJ_APP_ID");
                appSecret = getEnvVariable("FEISHU_TJ_APP_SECRET");
                receiveId = getEnvVariable("FEISHU_TJ_DEFAULT_RECEIVE_ID");
            }
            
            // 验证必要的配置参数
            validateFeishuConfig(appId, appSecret, receiveId);
            
            // 获取访问令牌
            String accessToken = getFeishuAccessToken(appId, appSecret);
            
            // 发送消息
            Map<String, Object> result = sendFeishuMessage(accessToken, receiveId, receiveIdType, content);
            
            // 添加原始消息文本到返回数据中
            result.put("text", content);
            
            return result;
            
        } catch (Exception e) {
            log.error("发送飞书消息失败", e);
            throw new RuntimeException("发送飞书消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证飞书配置
     */
    private void validateFeishuConfig(String appId, String appSecret, String receiveId) {
        if (appId == null || appId.trim().isEmpty()) {
            throw new RuntimeException("缺少必要的环境变量: FEISHU_APP_ID");
        }
        if (appSecret == null || appSecret.trim().isEmpty()) {
            throw new RuntimeException("缺少必要的环境变量: FEISHU_APP_SECRET");
        }
        if (receiveId == null || receiveId.trim().isEmpty()) {
            throw new RuntimeException("缺少必要的环境变量: FEISHU_DEFAULT_RECEIVE_ID");
        }
    }
    
    /**
     * 获取飞书访问令牌
     */
    private String getFeishuAccessToken(String appId, String appSecret) {
        try {
            // 构建获取认证token的curl命令
            String[] tokenCommand = {
                "curl", "-X", "POST",
                "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
                "-H", "Content-Type: application/json",
                "-d", objectMapper.writeValueAsString(Map.of(
                    "app_id", appId,
                    "app_secret", appSecret
                ))
            };
            
            // 执行命令获取token
            Process tokenProcess = Runtime.getRuntime().exec(tokenCommand);
            BufferedReader tokenReader = new BufferedReader(new InputStreamReader(tokenProcess.getInputStream()));
            StringBuilder tokenResponse = new StringBuilder();
            String line;
            while ((line = tokenReader.readLine()) != null) {
                tokenResponse.append(line);
            }
            
            int exitCode = tokenProcess.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("获取token失败，退出码: " + exitCode);
            }
            
            // 解析token响应
            Map<String, Object> tokenResult = objectMapper.readValue(tokenResponse.toString(), Map.class);
            
            if (!Integer.valueOf(0).equals(tokenResult.get("code"))) {
                throw new RuntimeException("获取Token失败: " + tokenResult);
            }
            
            return (String) tokenResult.get("tenant_access_token");
            
        } catch (Exception e) {
            log.error("获取飞书访问令牌失败", e);
            throw new RuntimeException("获取飞书访问令牌失败: " + e.getMessage());
        }
    }
    
    /**
     * 发送飞书消息
     */
    private Map<String, Object> sendFeishuMessage(String accessToken, String receiveId, String receiveIdType, String content) {
        try {
            // 构建发送消息的curl命令
            String[] sendCommand = {
                "curl", "-X", "POST",
                "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=" + receiveIdType,
                "-H", "Authorization: Bearer " + accessToken,
                "-H", "Content-Type: application/json",
                "-d", objectMapper.writeValueAsString(Map.of(
                    "receive_id", receiveId,
                    "msg_type", "text",
                    "content", objectMapper.writeValueAsString(Map.of("text", content))
                ))
            };
            
            // 执行命令发送消息
            Process sendProcess = Runtime.getRuntime().exec(sendCommand);
            BufferedReader sendReader = new BufferedReader(new InputStreamReader(sendProcess.getInputStream()));
            StringBuilder sendResponse = new StringBuilder();
            String line;
            while ((line = sendReader.readLine()) != null) {
                sendResponse.append(line);
            }
            
            int exitCode = sendProcess.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("发送消息失败，退出码: " + exitCode);
            }
            
            // 解析发送消息响应
            Map<String, Object> sendResult = objectMapper.readValue(sendResponse.toString(), Map.class);
            
            if (!Integer.valueOf(0).equals(sendResult.get("code"))) {
                throw new RuntimeException("发送消息失败: " + sendResult);
            }
            
            return (Map<String, Object>) sendResult.getOrDefault("data", new HashMap<>());
            
        } catch (Exception e) {
            log.error("发送飞书消息失败", e);
            throw new RuntimeException("发送飞书消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取环境变量
     */
    private String getEnvVariable(String key) {
        return System.getenv(key);
    }
}
